package com.wkbb.sports.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.wkbb.common.constants.RedisKeyConstant;
import com.wkbb.common.dto.ResultDTO;
import com.wkbb.common.dto.basic.EmployeeInfoDto;
import com.wkbb.common.dto.basic.OrganizationDto;
import com.wkbb.common.dto.basic.StudentInfoDto;
import com.wkbb.common.enums.RoleTypeEnum;
import com.wkbb.common.handler.JsonUtil;
import com.wkbb.common.redis.RedisTemplateUtil;
import com.wkbb.common.utils.TimeUtil;
import com.wkbb.sports.dto.*;
import com.wkbb.sports.enums.SportsModelTypeEnum;
import com.wkbb.sports.enums.SportsRuleTypeEnum;
import com.wkbb.sports.feign.BasicFeignService;
import com.wkbb.sports.mapper.*;
import com.wkbb.sports.model.*;
import com.wkbb.sports.service.RuleService;
import com.wkbb.sports.service.TrainService;
import com.wkbb.sports.utils.BeanBind;
import com.wkbb.sports.utils.SportsUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.*;


@Service
@Slf4j
public class TrainServiceImpl implements TrainService {
	@Autowired
	private RedisTemplateUtil redisTemplateUtil;
	
	@Autowired
	private HlifeDeviceMapper deviceMapper;
	
	@Autowired
	private HlifeTrainMapper trainMapper;

	@Autowired
	private HlifeTrainStudentMapper trainStudentMapper;

	@Autowired
	private HlifeTrainStudentAvgMapper trainStudentAvgMapper;

//	@Autowired
//	private HlifeTrainStudentDetailMapper trainStudentDetailMapper;
	
	@Autowired
	private HlifeRunningConfigMapper runningConfigMapper;

	@Autowired
	private HlifeUserMapper hlifeUserMapper;

	@Autowired
	private HlifePhysicalMapper physicalMapper;
	
	@Autowired
	private HlifePhysicalRuleMapper hlifePhysicalRuleMapper;

	@Autowired
	private HlifePhysicalRuleItemMapper hlifePhysicalRuleItemMapper;

	@Autowired
	private HlifePhysicalRulePlusesMapper hlifePhysicalRulePlusesMapper;
	
	@Autowired
	private HlifeOrgGradeMapper hlifeOrgGradeMapper;
	
	@Autowired
	private HlifeTrainStudentMapper hlifeTrainStudentMapper;
	
	@Autowired
	private HlifeTrainMapper hlifeTrainMapper;

	@Autowired
	private StatisticsMapper statisticsMapper;
	
	@Autowired
	private RuleService ruleService;

	@Autowired
	private BasicFeignService basicFeignService;

	@Override
	@Transactional(readOnly=true)
	public PhysicalAnalysisDto getStuPhysicalAnalysis(String studentId) {
		Map<String, Object> params = new HashMap<>();
		params.put("studentId",studentId);
		return trainMapper.getTeacherPhysicalAnalysis(params);
	}

	@Override
	@Transactional(readOnly=true)
	public PageInfo<TrainStuDto> getTrainListByStudent(Map<String, Object> params, int pageNo, int pageSize) {
		Page<TrainStuDto> page = PageHelper.startPage(pageNo, pageSize, true);
		List<TrainStuDto> trains = trainMapper.getTrainListByStudent(params);
		for (TrainStuDto dto:trains){
			dto.setModelTypeName(SportsModelTypeEnum.getDesc(dto.getModelType()));
		}
		PageInfo<TrainStuDto> pageInfo = new PageInfo<>(trains);
		pageInfo.setTotal(page.getTotal());
		return pageInfo;
	}

	@Override
	@Transactional(readOnly=true)
	public TrainStuDto getTrainStudent(Map<String, Object> params) {
		return trainMapper.getTrainStudent(params);
	}

	@Override
	@Transactional(readOnly=true)
	public ResultDTO<LatelStuSportDto> getLatelyStuSport(Map<String, Object> params) {
		List<LatelStuSportDto> list = trainMapper.getLatelyStuSport(params);
		LatelStuSportDto data;
//		log.info("getLatelyStuSport---list:{}", JsonUtil.stringify(list));
		if (!list.isEmpty() && list.get(0)!=null){
			data = list.get(0);
			params.put("sportDtos",true);
			List<LatelStuSportDto> sportDtos = trainMapper.getLatelyStuSport(params);
			if (!sportDtos.isEmpty() && sportDtos.get(0)!=null){
				data.setSportDtos(sportDtos);
			}
		}else{
			data = new LatelStuSportDto();
			data.setTotalTrainCount(0);
			data.setTotalTrainTime(0);
			data.setAvgAMinuteCount(0);
			data.setFastAMinuteCount(0);
			data.setSportDtos(new ArrayList<>());
		}
		return ResultDTO.successResult(data);
	}

	@Transactional(rollbackFor = Exception.class)
	@Override
	public int modifyDevices(List<DeviceDto> devices) throws Exception {
		BeanBind bind = new BeanBind(DeviceDto.class, HlifeDevice.class);
		int count = 0;
		for(DeviceDto device : devices) {
			HlifeDevice dev = (HlifeDevice)bind.bindBean(device);
			//跑步设备分组无需授权
			if (device.getProjectKind() == 2){
				deviceMapper.deleteDevice(dev);
				if(deviceMapper.getByMac(device.getDeviceId()) == null) {
					deviceMapper.insert(dev);
				}else {
					deviceMapper.update(dev);
				}
				count ++;
			}else{
				HlifeDeviceAuthorization hlifeDeviceAuthorization =  trainMapper.queryDeviceAuthorization(device.getMacAddress());
				if (hlifeDeviceAuthorization != null){
					deviceMapper.deleteDevice(dev);
					if(deviceMapper.getByMac(device.getDeviceId()) == null) {
						deviceMapper.insert(dev);
					}else {
						deviceMapper.update(dev);
					}
					count ++;
				}
			}
		}
		return count;
	}

	@Override
	@Transactional(readOnly = true)
	public List<HlifeDevice> queryDeviceList(Map<String, Object> params) throws Exception {
		params.put("status",1);
		List<HlifeDevice> result = deviceMapper.getListByMapParams(params);
		List<HlifeDevice> dtos = new ArrayList<>();

		//跑步主机授权设备列表获取
		List<HlifeDevice> pbList = deviceMapper.getPaobuList();
		for(HlifeDevice dev : pbList) {
			dev.setName("A1");
			dev.setGroupIndex(1);
			dev.setGroupName("A");
			dev.setMacAddress(dev.getDeviceId());
			dev.setProjectKind((byte) 0);
			dev.setDeviceType((byte) 0);
			dtos.add(dev);
		}

		dtos.addAll(result);
//		BeanBind bind = new BeanBind(HlifeDevice.class, DeviceDto.class);
//		for(HlifeDevice dev : result) {
//			DeviceDto dto = (DeviceDto)bind.bindBean(dev);
//			dtos.add(dto);
//		}
		return dtos;
	}

	@Transactional(rollbackFor = Exception.class)
	@Override
	public HlifeTrain addTrain(TrainDto trainDto)throws Exception{
		Map<String,Object> params = new HashMap<>();
		params.put("checkCode", trainDto.getCheckCode());
		HlifeTrain rtrain = trainMapper.getTrain(params);
		
		if(null != rtrain){
			return rtrain;
		}
		
		BeanBind bind = new BeanBind(TrainDto.class, HlifeTrain.class);
		HlifeTrain train = (HlifeTrain)bind.bindBean(trainDto);
		Date trainDate = TimeUtil.toDateYYYY_MM_DD(TimeUtil.toString(train.getStartTime(),TimeUtil.YYYY_MM_DD));
		train.setTrainDate(trainDate);
		train.setFpMode(0);
		Date curr = new Date();
		train.setCreateTime(curr);
		train.setUpdateTime(curr);
		trainMapper.insert(train);

		if (trainDto.getGroups() != null && !trainDto.getGroups().isEmpty()){
			List<HlifeTrainGroup> list = new ArrayList<>();
			BeanBind bind1  = new BeanBind(TrainGroupDto.class, HlifeTrainGroup.class);
			for(TrainGroupDto dto : trainDto.getGroups()) {
				HlifeTrainGroup group = (HlifeTrainGroup)bind1.bindBean(dto);
				group.setTrainId(train.getId());
				list.add(group);
			}
			trainMapper.insertGroupBatch(list);
		}

		if (trainDto.getStudents() != null && !trainDto.getStudents().isEmpty()){
			List<HlifeTrainStudent> students = new ArrayList<>();
			BeanBind bind1  = new BeanBind(TrainStudentDto.class, HlifeTrainStudent.class);
			if(train.getProjectKind() == 2) {
				RunningConfigDto runningConfigDto = trainDto.getRuningConfig();
				HlifeRunningConfig config = new HlifeRunningConfig();
				config.setTrainId(train.getId());
				config.setCircleCount(runningConfigDto.getCircleCount());
				config.setCircleInterval(runningConfigDto.getCircleInterval());
				config.setFirstCircleInterval(runningConfigDto.getFirstCircleInterval());
				config.setFirstCircleWhole(runningConfigDto.getFirstCircleWhole());
				runningConfigMapper.insert(config);
				train.setRuningConfig(config);
			}
			for(TrainStudentDto dto : trainDto.getStudents()) {
				HlifeTrainStudent student = (HlifeTrainStudent)bind1.bindBean(dto);
				student.setTrainId(train.getId());
				student.setOrgId(train.getOrgId());
				student.setGradeId(train.getGradeId());
				student.setGradeName(train.getGradeName());
				student.setClassId(train.getClassId());
				student.setClassName(train.getClassName());
				student.setProjectId(train.getProjectId());
				student.setTeacherId(train.getTeacherId());
				students.add(student);
			}
			trainStudentMapper.insertBatch(students);
		}
		trainDto.setId(train.getId());
		String redisKey = RedisKeyConstant.SPORTS + "getTrain:"+train.getId();
		redisTemplateUtil.set(redisKey,trainDto);
		log.info("trainDto:"+trainDto);
//		ExecutorService executorService = Executors.newFixedThreadPool(1);
//		executorService.submit(() -> {
//			try{
//				//敏捷业务
//				if (trainDto.getStudents() != null && !trainDto.getStudents().isEmpty()){
//					List<HlifeTrainStudent> students = new ArrayList<>();
//					BeanBind bind1  = new BeanBind(TrainStudentDto.class, HlifeTrainStudent.class);
////					BeanBind bind2  = new BeanBind(TrainStudentDetailDto.class, HlifeTrainStudentDetail.class);
//					if(train.getProjectKind() == 2) {
//						RunningConfigDto runningConfigDto = trainDto.getRuningConfig();
//						HlifeRunningConfig config = new HlifeRunningConfig();
//						config.setTrainId(train.getId());
//						config.setCircleCount(runningConfigDto.getCircleCount());
//						config.setCircleInterval(runningConfigDto.getCircleInterval());
//						config.setFirstCircleInterval(runningConfigDto.getFirstCircleInterval());
//						config.setFirstCircleWhole(runningConfigDto.getFirstCircleWhole());
//						runningConfigMapper.insert(config);
//						train.setRuningConfig(config);
//					}
//					for(TrainStudentDto dto : trainDto.getStudents()) {
//						HlifeTrainStudent student = (HlifeTrainStudent)bind1.bindBean(dto);
//						student.setTrainId(train.getId());
//						student.setOrgId(train.getOrgId());
//						student.setGradeId(train.getGradeId());
//						student.setGradeName(train.getGradeName());
//						student.setClassId(train.getClassId());
//						student.setClassName(train.getClassName());
//						student.setProjectId(train.getProjectId());
//						//student.setProjectName(train.getProjectName());
//						student.setTeacherId(train.getTeacherId());
//						student.setCreateBy(train.getCreateBy());
//						students.add(student);
//
////						if (dto.getDetails() != null && !dto.getDetails().isEmpty()){
////							List<HlifeTrainStudentDetail> details = new ArrayList<>();
////							for(TrainStudentDetailDto studetail :dto.getDetails()){
////								studetail.setTrainId(train.getId());
////								studetail.setStudentId(student.getStudentId());
////								studetail.setProjectKind(train.getProjectKind());
////								HlifeTrainStudentDetail dt = (HlifeTrainStudentDetail)bind2.bindBean(studetail);
////								details.add(dt);
////							}
////							trainStudentDetailMapper.insertBatch(details);
////						}
//					}
//					trainStudentMapper.insertBatch(students);
//				}
//				executorService.shutdown();
//			}catch(Exception e){
//				log.error(e.getMessage());
//			}
//		});
		return train;
	}

	@Override
	@Transactional(readOnly = true)
	public TrainDto getTrain(long trainId) throws Exception {
		String redisKey = RedisKeyConstant.SPORTS + "getTrain:"+trainId;
		TrainDto dto = (TrainDto)redisTemplateUtil.get(redisKey);
		if (dto != null) return dto;
		HlifeTrain train = trainMapper.getByPrimaryKey(trainId);
		if (train != null){
			BeanBind bind = new BeanBind(HlifeTrain.class, TrainDto.class);
			dto = (TrainDto)bind.bindBean(train);
			Map<String, Object> params = new HashMap<>();
			params.put("trainId", trainId);
			dto.setStudentAvgs(trainStudentAvgMapper.getListByMapParams(params));
			dto.setStudents(queryTrainStudentList(params));
			if (dto.getStudents().isEmpty()){
				dto.setGroups(queryTrainGroupList(trainId));
			}
			HlifeRunningConfig config = runningConfigMapper.getByPrimaryKey(trainId);
			bind = new BeanBind(HlifeRunningConfig.class, RunningConfigDto.class);
			RunningConfigDto configDto = (RunningConfigDto)bind.bindBean(config);
			dto.setRuningConfig(configDto);
			redisTemplateUtil.set(redisKey,dto);
		}
		return dto;
	}

	public List<TrainGroupDto> queryTrainGroupList(Long trainId) throws Exception {
		List<HlifeTrainGroup> groups = trainMapper.queryTrainGroupList(trainId);
		List<TrainGroupDto> groupDtos = new ArrayList<>();
		BeanBind bind = new BeanBind(HlifeTrainGroup.class, TrainGroupDto.class);
		for (HlifeTrainGroup std:groups){
			TrainGroupDto dto = (TrainGroupDto)bind.bindBean(std);
			groupDtos.add(dto);
		}
        return groupDtos;
	}

	@SuppressWarnings("unchecked")
	@Override
	@Transactional(readOnly = true)
	public List<TrainStudentDto> queryTrainStudentList(Map<String, Object> params) throws Exception {
		List<HlifeTrainStudent> students = trainStudentMapper.getListByMapParams(params);
		List<TrainStudentDto> studentDtos = new ArrayList<>();
		BeanBind bind = new BeanBind(HlifeTrainStudent.class, TrainStudentDto.class);
//		BeanBind bindDetail = new BeanBind(HlifeTrainStudentDetail.class, TrainStudentDetailDto.class);
//		Map<String, Object> args = new HashMap<>();
		for (HlifeTrainStudent std:students){
			TrainStudentDto dto = (TrainStudentDto)bind.bindBean(std);
//			args.put("studentId", std.getStudentId());
//			args.put("trainId", std.getTrainId());
//			List<HlifeTrainStudentDetail> details = trainStudentDetailMapper.getListByMapParams(args);
//			dto.setDetails((List<TrainStudentDetailDto>)bindDetail.bindBeans(details));
			studentDtos.add(dto);
		}
        return studentDtos;
	}

	@Override
	@Transactional(readOnly = true)
	public PageInfo<TrainDto> queryTrainList(Map<String, Object> params, int pageNo, int pageSize) throws Exception {
		Page<TrainDto> page = PageHelper.startPage(pageNo, pageSize, true);
		List<HlifeTrain> trains = trainMapper.getListByMapParams(params);
		List<TrainDto> dtos = new ArrayList<>();
		BeanBind bind = new BeanBind(HlifeTrain.class, TrainDto.class);
		for(HlifeTrain train : trains) {
			TrainDto dto = (TrainDto)bind.bindBean(train);
			dtos.add(dto);
		}
        PageInfo<TrainDto> pageInfo = new PageInfo<TrainDto>(dtos);
        pageInfo.setTotal(page.getTotal());
        return pageInfo;
	}

	@Override
	@Transactional(readOnly = true)
	public StudentTrainInfoDto getStudentTrainInfo(Long trainId, Long studentId) throws Exception {
		Map<String, Object> params = new HashMap<>();
		params.put("trainId", trainId);
		params.put("studentId", studentId);
		HlifeTrainStudent stu = trainStudentMapper.getByMapParams(params);
		HlifeTrain train = trainMapper.getByPrimaryKey(trainId);
//		List<HlifeTrainStudentDetail> details = trainStudentDetailMapper.getListByMapParams(params);
		StudentTrainInfoDto info = new StudentTrainInfoDto();
		
		info.setProjectKind(train.getProjectKind());
		info.setMarkType(train.getMarkType());
		info.setModelType(train.getModelType());
		
		info.setStudentId(stu.getStudentId());
		info.setClassId(stu.getClassId());
		info.setGradeId(stu.getGradeId());
		info.setSex(stu.getSex());
		info.setAchievement(stu.getAchievement());
		info.setTotalScore(stu.getTotalScore());
		return info;
	}


	private void logError(Throwable e) {
		StringWriter sw = new StringWriter();
		PrintWriter pw = new PrintWriter(sw);
		e.printStackTrace(pw);
		pw.flush();
		log.error(sw.toString());
		
	}

	@Override
	@Transactional(readOnly = true)
	public PageInfo<TrainStudentDto> queryTrainStudentList4Persion(Map<String, Object> params, Integer pageNo, Integer pageSize) throws Exception {
		Page<TrainStudentDto> page = PageHelper.startPage(pageNo, pageSize, true);
		List<HlifeTrainStudent> students = trainStudentMapper.getListByMapParams(params);
		List<TrainStudentDto> studentDtos = new ArrayList<>();
		BeanBind bind = new BeanBind(HlifeTrainStudent.class, TrainStudentDto.class);
		for(int i = 0 ; i < students.size(); i++) {
			HlifeTrainStudent std = students.get(i);
			TrainStudentDto dto = (TrainStudentDto)bind.bindBean(std);
			HlifeTrain train = trainMapper.getByPrimaryKey(std.getTrainId());
			dto.setModelType(train.getModelType());
			dto.setProjectKind(train.getProjectKind());
			dto.setStartTime(train.getStartTime());
			dto.setTeacher(getTeacher(train));
			studentDtos.add(dto);
		}
        PageInfo<TrainStudentDto> pageInfo = new PageInfo<TrainStudentDto>(studentDtos);
        pageInfo.setTotal(page.getTotal());
        return pageInfo;
	}

	private String getTeacher(HlifeTrain hlifeTrain) {

		Long orgId = hlifeTrain.getOrgId();
		Long teacherId = hlifeTrain.getTeacherId();

		Map<String, Object> params = new HashMap<>();
		params.put("orgId", orgId);
		params.put("userType", (byte) RoleTypeEnum.TEACHER.getValue());
		params.put("userId", teacherId);
		HlifeUser user = hlifeUserMapper.getByMapParams(params);
		if(user != null) {
			return user.getUserName();
		}

		ResultDTO<EmployeeInfoDto> result = basicFeignService.getEmployeeInfo(hlifeTrain.getOrgId(), hlifeTrain.getTeacherId());
		EmployeeInfoDto employeeInfoDto = result.getData();
		if(employeeInfoDto != null) {
			//保存数据
			HlifeUser hlifeUser = new HlifeUser();
			hlifeUser.setUserType((byte) RoleTypeEnum.TEACHER.getValue());
			hlifeUser.setOrgId(orgId);
			hlifeUser.setOrgName(employeeInfoDto.getOrgName());
			hlifeUser.setUserId(employeeInfoDto.getUserId());
			hlifeUser.setUserName(employeeInfoDto.getName());
			hlifeUser.setMobile(employeeInfoDto.getMobile());
			hlifeUser.setSex(SportsUtils.getSexValue(employeeInfoDto.getSex()).byteValue());
			hlifeUser.setHeadImg(employeeInfoDto.getHeadImgUrl());
			hlifeUser.setUserNo(employeeInfoDto.getJobNo());
			hlifeUserMapper.insert(hlifeUser);
			return employeeInfoDto.getName();
		}
		return null;
	}

	@Override
	@Transactional(readOnly = true)
	public Double queryTrainStudentSummary(Map<String, Object> params) throws Exception {
		return trainStudentMapper.queryTrainStudentSummary(params);
	}

	@Override
	@Transactional(readOnly = true)
	public Map<String, Object> getTeacherTrainWholeStat(Long orgId, Long userId)
	{
		Map<String, Object> wholeStatMap = new HashMap<>();

		Map<String, Object> teacherTrainStatParams = new HashMap<>();
		teacherTrainStatParams.put("orgId",orgId);
		teacherTrainStatParams.put("teacherId",userId);

		BCDTBasicDto dto = statisticsMapper.getOrgDataCount(teacherTrainStatParams);
		if(null!= dto)
		{
			wholeStatMap.put("studentCount",dto.getStudentCount());
			wholeStatMap.put("teacherCount",dto.getTeacherCount());
			wholeStatMap.put("classCount",dto.getClassCount());
		}
		TrainAnalysisDto teacherTrainStat = trainMapper.getTeacherTrainStat(teacherTrainStatParams);
		wholeStatMap.put("trainTotalTime", teacherTrainStat.getTrainTotalTime());
		wholeStatMap.put("trainCount", teacherTrainStat.getTrainCount());
//		wholeStatMap.put("trainTotalTime",null==teacherTrainStatMap.get("trainTotalTime")?0:teacherTrainStatMap.get("trainTotalTime"));
//		wholeStatMap.put("trainCount",null==teacherTrainStatMap.get("trainCount")?0:teacherTrainStatMap.get("trainCount"));
		return wholeStatMap;
	}

	@Override
	@Transactional(readOnly = true)
	public Map<String, Object> getTeacherTrainStat(Long orgId, Long teacherId, Integer projectKind)
	{
		Map<String, Object> statMap = new HashMap<>();

		//根据项目类型查询项目
//		Map<String, Object> projectParams = new HashMap<>();
//		projectParams.put("orgId",orgId);
//		projectParams.put("projectKind",projectKind);
//
//		List<PhysicalDto> physicalList = physicalMapper.getOrgPhysicalList(projectParams);
//		List<Long> physicalIdList = new ArrayList<>();
//		for(PhysicalDto physical : physicalList)
//		{
//			physicalIdList.add(physical.getId());
//		}
//		String projectIds = StringUtils.strip(physicalIdList.toString(),"[]");

		Map<String, Object> lastTrainParams = new HashMap<>();
		lastTrainParams.put("orgId",orgId);
		lastTrainParams.put("teacherId",teacherId);
		lastTrainParams.put("projectKind",projectKind);
		HlifeTrain hlifeTrain = trainMapper.getTeacherLastTrain(lastTrainParams);
		if(null!=hlifeTrain)
		{
			Date endDate = hlifeTrain.getTrainDate();
			if(null==endDate)
			{
				endDate = new Date();
			}
			Date beginDate = TimeUtil.getDateAfterMonths(endDate,-2);
			String strBeginDate = TimeUtil.toStringYYYY_MM_DD(beginDate);
			String strEndDate = TimeUtil.toStringYYYY_MM_DD(endDate);
			statMap.put("beginDate",strBeginDate);
			statMap.put("endDate",strEndDate);

			//成绩分布统计
			Map<String, Object> distributeParams = new HashMap<>();
			distributeParams.put("orgId",orgId);
			distributeParams.put("teacherId",teacherId);
			distributeParams.put("projectKind",projectKind);
//			distributeParams.put("projectIds",projectIds);
			distributeParams.put("beginDate",strBeginDate);
			distributeParams.put("endDate",strEndDate);
			List<Map<String, Object>> distributeList = trainStudentMapper.getTeacherTrainDistributeStat(distributeParams);
			if(!distributeList.isEmpty()) {
			    if(null!=distributeList.get(0)) {
                    for (Map<String, Object> distribute : distributeList){
						distributeParams.put("classId",distribute.get("class_id"));
						Page<TrainStudentDto> page = PageHelper.startPage(1, 10, true);
						PageInfo<TrainStudentDto> pageInfo = new PageInfo<TrainStudentDto>(trainStudentMapper.getTeacherTrainFlunkStudentList(distributeParams));
						pageInfo.setTotal(page.getTotal());
						distribute.put("flunkList",pageInfo.getList());
					}
					statMap.put("distributeList", distributeList);
				}
                else
                {
					statMap.put("distributeList", new ArrayList<Map<String, Object>>());
                }
			}

//			//重点关注学生
//			Map<String, Object> flunkParams = new HashMap<>();
//			flunkParams.put("orgId",orgId);
//			flunkParams.put("teacherId",teacherId);
//			flunkParams.put("projectIds",projectIds);
//			flunkParams.put("beginDate",strBeginDate);
//			flunkParams.put("endDate",strEndDate);
//
//			Page<HlifeTrainStudent> page = PageHelper.startPage(1, 10, true);
//			PageInfo<HlifeTrainStudent> pageInfo = new PageInfo<HlifeTrainStudent>(trainStudentMapper.getTeacherTrainFlunkStudentList(flunkParams));
//			pageInfo.setTotal(page.getTotal());
//			statMap.put("flunkList",pageInfo.getList());
		}

		return statMap;
	}

	@Override
	@Transactional(readOnly = true)
	public PageInfo<TrainStudentDto> getTrainFlunkStudentPageList(Long orgId, Long classId, Integer projectKind, String beginDate, String endDate, Integer pageNo, Integer pageSize)
	{
		//根据项目类型查询项目
//		Map<String, Object> projectParams = new HashMap<>();
//		projectParams.put("orgId",orgId);
//		projectParams.put("projectKind",projectKind);
//		List<PhysicalDto> physicalList = physicalMapper.getOrgPhysicalList(projectParams);
//		List<Long> physicalIds = new ArrayList<>();
//		for(PhysicalDto physical : physicalList)
//		{
//			physicalIds.add(physical.getId());
//		}

		Map<String, Object> flunkParams = new HashMap<>();
		flunkParams.put("orgId",orgId);
		flunkParams.put("classId",classId);
		flunkParams.put("projectKind",projectKind);
//		flunkParams.put("projectIds", StringUtils.strip(physicalIds.toString(),"[]"));
		flunkParams.put("beginDate",beginDate);
		flunkParams.put("endDate",endDate);

		Page<TrainStudentDto> page = PageHelper.startPage(pageNo, pageSize, true);
		PageInfo<TrainStudentDto> pageInfo = new PageInfo<TrainStudentDto>(trainStudentMapper.getTeacherTrainFlunkStudentList(flunkParams));
		pageInfo.setTotal(page.getTotal());
		return pageInfo;
	}

	@Override
	public Map<String,Object> getTeacherTrainStudentReport(Long orgId, Long studentId, Integer projectKind, String beginDate, String endDate)
	{
		Map<String, Object> statMap = new HashMap<>();

		//根据项目类型查询项目
		Map<String, Object> projectParams = new HashMap<>();
		projectParams.put("orgId",orgId);
		projectParams.put("projectKind",projectKind);
//		List<PhysicalDto> physicalList = physicalMapper.getOrgPhysicalList(projectParams);
//		List<Long> physicalIds = new ArrayList<>();
//		for(PhysicalDto physical : physicalList)
//		{
//			physicalIds.add(physical.getId());
//		}

		//查询历史的学生训练数据
		Map<String, Object> params = new HashMap<>();
		params.put("orgId", orgId);
		params.put("studentId", studentId);
		params.put("projectKind",projectKind);
//		params.put("projectIds", StringUtils.strip(physicalIds.toString(),"[]"));
		params.put("beginDate", beginDate);
		params.put("endDate", endDate);

		Map<String, Object> achievementHistoryStatMap = trainStudentMapper.getTrainStudentHistoryStat(params);
		statMap.put("achievementHistoryStatMap", achievementHistoryStatMap);//历史训练成绩统计

		//训练列表
		List<HlifeTrainStudent> trainList = trainStudentMapper.getStudentTrainList(params);
		statMap.put("trainList", trainList);

		return statMap;
	}

	@Override
	@Transactional(readOnly = true)
	public Map<String,Object> getTrainStudentReport(Long orgId, Long studentId, Integer projectKind, String beginDate, String endDate)
			throws Exception {
		Map<String, Object> statMap = new HashMap<>();
		//根据项目类型查询项目
		Map<String, Object> projectParams = new HashMap<>();
		projectParams.put("orgId",orgId);
		projectParams.put("projectKind",projectKind);
		//查询历史的学生训练数据
		Map<String, Object> params = new HashMap<>();
		params.put("orgId", orgId);
		params.put("studentId", studentId);
		params.put("projectKind",projectKind);
		//最近一次训练结果
		TrainDto train = trainMapper.getStudentLastTrain(params);
		if (train != null){
			Map<String, Object> stuParams = new HashMap<>();
			stuParams.put("trainId", train.getId());
			List<HlifeTrainStudent> students = trainStudentMapper.getListByMapParams(stuParams);
			List<TrainStudentDto> studentDtos = new ArrayList<>();
			BeanBind bind = new BeanBind(HlifeTrainStudent.class, TrainStudentDto.class);
			for (HlifeTrainStudent std:students){
				TrainStudentDto dto = (TrainStudentDto)bind.bindBean(std);
				studentDtos.add(dto);
			}
			train.setStudents(studentDtos);
			statMap.put("train",train);
		}
		params.put("beginDate", beginDate);
		params.put("endDate", endDate);

		//最近两个月训练趋势
		List<TrainTrendDto> trainTrends = trainStudentMapper.getStudentTrainTrend(params);
		statMap.put("trainTrends", trainTrends);
		return statMap;
	}

	/**
	 * 体育训练报告(家长)
	 * */
	@Override
	@Transactional(readOnly = true)
	public Map<String,Object> getSportsReportToFamily(Long orgId, Long userId, String trainDate, Long projectId)
	{

		Map<String, Object> reMap = new HashMap<>();
		reMap.put("trainDate", trainDate);//训练日期

		try {
			ResultDTO<List<StudentInfoDto>> studentInfoResult = basicFeignService.getStudentInfoByStudent(orgId, userId);
			if (studentInfoResult.isSuccess() && !studentInfoResult.getData().isEmpty()) {

				StudentInfoDto studentInfo = studentInfoResult.getData().get(0);
				reMap.put("studentInfo", studentInfo);//学生信息

				PhysicalDto physicalDto = null;
				List<PhysicalDto> physicalList = this.getPhysicalRules(orgId, projectId);
				if (!physicalList.isEmpty()) {
					physicalDto = physicalList.get(0);
				}

				//转换一下规则年级
				Map<String, Object> gradeParams = new HashMap<>();
				gradeParams.put("orgId", orgId);
				gradeParams.put("gradeId", studentInfo.getGradeId());
				HlifeOrgGrade hlifeOrgGrade = hlifeOrgGradeMapper.getByMapParams(gradeParams);

				//查询当天的学生训练数据
				Map<String, Object> params = new HashMap<>();
				params.put("orgId", orgId);
				params.put("studentId", userId);
				params.put("trainDate", trainDate);//训练日期
				params.put("projectId", projectId);

				List<TrainReportStudentDto> trainReportStudentList = new ArrayList<>();
				List<HlifeTrainStudent> trainAchievementList = hlifeTrainStudentMapper.getTrainAchievementList(params);
				for (HlifeTrainStudent trainStudent : trainAchievementList) {
					TrainReportStudentDto trainReportStudentDto = new TrainReportStudentDto();
					BeanUtils.copyProperties(trainStudent, trainReportStudentDto);
					Map<String, Object> markMap = this.calPhysicalScore(physicalDto, orgId, hlifeOrgGrade.getRuleGradeId(), this.getSexType(studentInfo.getSex()).byteValue(), trainStudent.getAchievement());
					trainReportStudentDto.setFullScore("" + (Double) markMap.get("fullScore"));
					trainReportStudentDto.setFullValue((String) markMap.get("fullValue"));
					trainReportStudentDto.setFullAchievement((String) markMap.get("fullAchievement"));
					trainReportStudentDto.setPlusesScore((String) markMap.get("plusesScore"));
					trainReportStudentDto.setPlusesValue((String) markMap.get("plusesValue"));
					trainReportStudentDto.setPlusesAchievement((String) markMap.get("plusesAchievement"));
					trainReportStudentList.add(trainReportStudentDto);
				}
				reMap.put("achievementList", trainReportStudentList);//训练成绩

				//查询历史的学生训练数据
				Map<String, Object> historyParams = new HashMap<>();
				historyParams.put("orgId", orgId);
				historyParams.put("studentId", userId);
				historyParams.put("projectId", projectId);
				historyParams.put("trainDate", trainDate);//训练日期

				List<HlifeTrainStudent> achievementHistoryList = hlifeTrainStudentMapper.getTrainAchievementHistoryList(historyParams);
				reMap.put("historyAchievementList", achievementHistoryList);//历史训练成绩
				//计算满分及加分项规则值
				if (!trainAchievementList.isEmpty()) {
					Map<String, Object> marksMap = new HashMap<>();
					HlifeTrainStudent achievementStudent = trainAchievementList.get(0);
					if (null != achievementStudent.getScore() && achievementStudent.getScore() > 0) {
						if (null != physicalDto) {
							Map<String, Object> markMap = this.calPhysicalScore(physicalDto, achievementStudent.getOrgId(), hlifeOrgGrade.getRuleGradeId(), achievementStudent.getSex(), achievementStudent.getAchievement());
							marksMap.put("fullMarksScore", markMap.get("fullMarksScore"));
							marksMap.put("fullMarksValue", markMap.get("fullMarksValue"));
							marksMap.put("plusesMarksScore", markMap.get("plusesMarksScore"));
							marksMap.put("plusesMarksValue", markMap.get("plusesMarksValue"));
						}
					}

					reMap.put("marksMap", marksMap);
				}

				//标尺顺序
				String[] markArr = {"0to20", "20to40", "40to60", "60to80", "80to100", "100to120", "120to"};
				reMap.put("markList", Arrays.asList(markArr));

				//查询班级训练数据
				List<Map<String, Object>> classStatList = new ArrayList<>();

				Map<String, Object> classParams = new HashMap<>();
				classParams.put("orgId", orgId);
				classParams.put("classId", studentInfo.getClassId());
				classParams.put("projectId", projectId);//项目ID
				classParams.put("studentId", userId);
				classParams.put("trainDate", trainDate);//训练日期
				List<HlifeTrain> achievementClassList = hlifeTrainMapper.getAchievementClassList(classParams);
				for (HlifeTrain hlifeTrain : achievementClassList) {

					Map<String, Object> classStatMap = new HashMap<>();
					classStatMap.put("classStat", hlifeTrain);//班级数据

					Map<String, Object> classStudentParams = new HashMap<>();
					classStudentParams.put("orgId", orgId);
					classStudentParams.put("classId", studentInfo.getClassId());
					classStudentParams.put("projectId", projectId);//项目ID
					classStudentParams.put("trainId", hlifeTrain.getId());//训练ID

					List<Map<String, Integer>> classAchievementStatList = hlifeTrainStudentMapper.getAchievementStudentClassStat(classStudentParams);
					classStatMap.put("classStatList", classAchievementStatList);

					//成绩排行榜
					Map<String, Object> rankingParams = new HashMap<>();
					rankingParams.put("orgId", orgId);
					rankingParams.put("classId", studentInfo.getClassId());
					rankingParams.put("projectId", projectId);//项目ID
					rankingParams.put("trainId", hlifeTrain.getId());//训练ID
					rankingParams.put("sex", SportsUtils.getSexValue(studentInfo.getSex()));
					List<HlifeTrainStudent> rankingList = hlifeTrainStudentMapper.getAchievementStudentRankingList(rankingParams);
					classStatMap.put("rankingList", rankingList);
					for (HlifeTrainStudent achievementStudent : rankingList) {
						if (achievementStudent.getStudentId().equals(userId)) {
							classStatMap.put("studentAchievement", achievementStudent.getScore() + achievementStudent.getPlusScore());
							break;
						}
					}

					classStatList.add(classStatMap);
				}
				reMap.put("classTabList", classStatList);//班级数据

			}

		}
		catch (Exception e)
		{
			log.error("getSportsReportToFamily异常",e);
		}
		return reMap;
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public HlifeDeviceAuthorizationLog authorizationDevices(HlifeDeviceAuthorizationLog deviceAuthorizationLog, String devices) {
//		log.info("authorizationDevices:"+ JsonUtil.stringify(deviceAuthorizationLog));
		String[] arr = devices.split(",");
		List<HlifeDeviceAuthorization> list = new ArrayList<>();
		for (String device:arr){
			HlifeDeviceAuthorization item = new HlifeDeviceAuthorization();
			item.setDeviceId(device);
			item.setProjectKind(deviceAuthorizationLog.getProjectKind());
			item.setLogId(deviceAuthorizationLog.getUniqueId());
			list.add(item);
		}
		int count = trainMapper.insertDeviceAuthorizationList(list);
		if (count > 0){
			deviceAuthorizationLog.setDeviceCount(count);
			trainMapper.insertDeviceAuthorizationLog(deviceAuthorizationLog);
		}
		return deviceAuthorizationLog;
	}

	@Override
	@Transactional(readOnly = true)
	public List<HlifeDeviceAuthorizationLog> getDeviceAuthorizationCount() {
		return trainMapper.getDeviceAuthorizationCount();
	}

	@Override
	@Transactional(readOnly = true)
	public PageInfo<HlifeDeviceAuthorizationLog> queryDeviceAuthorizationLogList(Byte projectKind, int pageNo, int pageSize) {
		PageInfo<HlifeDeviceAuthorizationLog> pageInfo = new PageInfo<>();
		Page<HlifeDeviceAuthorizationLog> page = PageHelper.startPage(pageNo, pageSize,false);
		List<HlifeDeviceAuthorizationLog> list = trainMapper.queryDeviceAuthorizationLogList(projectKind);
		pageInfo.setList(list);
		return pageInfo;
	}

	@Override
	@Transactional(readOnly = true)
	public HlifePadAuthorizationLog getPadAuthorizationStatus(String padId) {
		HlifePadAuthorizationLog padAuthorizationLog = trainMapper.getPadAuthorization(padId);
		if (padAuthorizationLog == null){
			HlifePadAuthorizationLog authorizationLog = new HlifePadAuthorizationLog();
			authorizationLog.setPadId(padId);
			HlifePadAuthorizationLog oldLog = trainMapper.getPadAuthorizationLog(authorizationLog);
			if (oldLog != null){
				return oldLog;
			}
		}
//		else{
//			if (padAuthorizationLog.getAuthorizationType() == 2 ){
//				padAuthorizationLog.setStatus(padAuthorizationLog.getEndTime().getTime() >= new Date().getTime() ? (byte) 2 : (byte) 0);
//			}
//		}
		return padAuthorizationLog;
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public int applyPadAuthorization(HlifePadAuthorizationLog padAuthorizationLog) {
		HlifePadAuthorizationLog oldLog = trainMapper.getPadAuthorizationLog(padAuthorizationLog);
		if (oldLog == null){
			int result = trainMapper.insertPadAuthorizationLog(padAuthorizationLog);
			if (result > 0) return 1;
		}else{
			if (!oldLog.getAuthorizationType().equals(padAuthorizationLog.getAuthorizationType())){
				oldLog.setStatus((byte) 3);
				trainMapper.updatePadAuthorizationLog(oldLog);
				int result = trainMapper.insertPadAuthorizationLog(padAuthorizationLog);
				if (result > 0) return 1;
			}
		}
		return 0;
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public int auditPadAuthorization(Long id, Byte status, String name) {
		HlifePadAuthorizationLog padAuthorizationLog = new HlifePadAuthorizationLog();
		padAuthorizationLog.setId(id);
		HlifePadAuthorizationLog oldLog = trainMapper.getPadAuthorizationLog(padAuthorizationLog);
		if (oldLog != null){
			oldLog.setStatus(status);
			oldLog.setAuditUser(name);
			Date startDate = new Date();
			oldLog.setAuditTime(startDate);
			if (oldLog.getAuthorizationType() == 2){
				oldLog.setStartTime(startDate);
				Calendar cal = Calendar.getInstance();
				cal.setTime(startDate);
				cal.add(Calendar.MONTH,1);
				oldLog.setEndTime(cal.getTime());
			}
			int updatePadAuthorizationLog = trainMapper.updatePadAuthorizationLog(oldLog);
			if (updatePadAuthorizationLog > 0){
				return trainMapper.insertPadAuthorization(oldLog.getId());
			}
		}
		return 0;
	}

	@Override
	@Transactional(readOnly = true)
	public PageInfo<HlifePadAuthorizationLog> queryPadAuthorizationLogList(String padId, int pageNo, int pageSize) {
		PageInfo<HlifePadAuthorizationLog> pageInfo = new PageInfo<>();
		Page<HlifePadAuthorizationLog> page = PageHelper.startPage(pageNo, pageSize,true);
		List<HlifePadAuthorizationLog> list = trainMapper.getPadAuthorizationLogList(padId);
		pageInfo.setTotal(page.getTotal());
		pageInfo.setList(list);
		return pageInfo;
	}

	@Override
	public List<HlifeDevice> queryOrgDeviceList(Map<String, Object> params) throws Exception {
		params.put("status",1);
		List<HlifeDevice> result = deviceMapper.getListByMapParams(params);
		return result;
//		List<DeviceDto> dtos = new ArrayList<>();
//		BeanBind bind = new BeanBind(HlifeDevice.class, DeviceDto.class);
//		for(HlifeDevice dev : result) {
//			DeviceDto dto = (DeviceDto)bind.bindBean(dev);
//			dtos.add(dto);
//		}
//		return dtos;
	}

	@Override
	@Transactional(readOnly = true)
	public PageInfo<HlifeDevice> getDevicePageList(Map<String, Object> params, int pageNo, int pageSize) {
		Page<HlifeDevice> page = PageHelper.startPage(pageNo, pageSize,true);
		PageInfo<HlifeDevice> pageInfo = new PageInfo<>(deviceMapper.getListByMapParams(params));
		pageInfo.setTotal(page.getTotal());
		return pageInfo;
	}

	@Override
	public void changeDeviceStatus(Long id, Integer status) {
		deviceMapper.changeDeviceStatus(id,status);
	}

	@Override
	@Transactional(readOnly = true)
	public PageInfo<HlifeDeviceAuthorization> queryDeviceAuthorizationList(Integer projectKind, int pageNo, int pageSize) {
		Page<HlifeDeviceAuthorization> page = PageHelper.startPage(pageNo, pageSize,true);
		PageInfo<HlifeDeviceAuthorization> pageInfo = new PageInfo<>(deviceMapper.queryDeviceAuthorizationList(projectKind));
		pageInfo.setTotal(page.getTotal());
		return pageInfo;
	}

	public List<PhysicalDto> getPhysicalRules(Long orgId,Long physicalId) {

		List<PhysicalDto> physicalList = new ArrayList<>();

		//取出项目
		OrganizationDto orgDto = getOrgDto(orgId);
		List<PhysicalDto> orgPhysicalList = physicalMapper.queryPhysicalListByOrg(orgId, orgDto.getProvinceId(), orgDto.getCityId());
		for(PhysicalDto physicalDto : orgPhysicalList)
		{
			if(physicalDto.getId().equals(physicalId))
			{
				physicalList.add(physicalDto);
				break;
			}
		}

		//取出项目规则
		String ids = getPhysicalIds(physicalList);
		List<PhysicalRuleDto> physicalRuleList = hlifePhysicalRuleMapper.queryRuleListByPhysicalIds(ids,null);
		List<PhysicalRuleItemDto> physicalRuleItemList = hlifePhysicalRuleItemMapper.queryRuleItemListByPhysicalIds(ids);
		List<PhysicalRulePlusesDto> physicalRulePlusList = hlifePhysicalRulePlusesMapper.queryRulePlusListByPhysicalIds(ids);

		for(PhysicalRuleDto rule : physicalRuleList) {
			for(PhysicalDto physical : physicalList) {
				if(compareValue(physical.getId(), rule.getPhysicalId())) {
					List<PhysicalRuleDto> list = physical.getRuleList();
					if(list == null) {
						list = new ArrayList<>();
						physical.setRuleList(list);
					}
					list.add(rule);
				}
			}
		}

		for(PhysicalRuleItemDto item : physicalRuleItemList) {
			for(PhysicalRuleDto rule : physicalRuleList) {
				if(compareValue(rule.getId(), item.getRuleId())) {
					List<PhysicalRuleItemDto> list = rule.getItemDtoList();
					if(list == null) {
						list = new ArrayList<>();
						rule.setItemDtoList(list);
					}
					list.add(item);
				}
			}
		}

		for(PhysicalRulePlusesDto plus : physicalRulePlusList) {
			for(PhysicalRuleDto rule : physicalRuleList) {
				if(compareValue(rule.getId(), plus.getRuleId())) {
					List<PhysicalRulePlusesDto> list = rule.getPlusesList();
					if(list == null) {
						list = new ArrayList<>();
						rule.setPlusesList(list);
					}
					list.add(plus);
				}
			}
		}
		return physicalList;
	}

	private OrganizationDto getOrgDto(Long orgId) {
		ResultDTO<OrganizationDto> resultDto = basicFeignService.getOrgById(orgId);

		OrganizationDto orgDto = resultDto.getData();

		if(orgDto == null) {
			return new OrganizationDto();
		}

		return orgDto;
	}
	
	private boolean compareValue(Number n1, Number n2) {
		if(n1 == null || n2 == null) {
			return false;
		}
		if(n1 instanceof Long) {
			return n1.longValue() == n2.longValue();
		}
		if(n1 instanceof Byte) {
			return n1.byteValue() == n2.byteValue();
		}
		return n1.intValue() == n2.intValue();
	}

	private String getPhysicalIds(List<PhysicalDto> physicalList) {
		Long[] ids = new Long[physicalList.size()];
		int i = 0;
		for(PhysicalDto physical : physicalList) {
			Long physicalId = physical.getId();
			ids[i] = physicalId;
			i++;
		}
		String arrays = Arrays.toString(ids);
		arrays = arrays.replace('[', '(');
		arrays = arrays.replace(']', ')');
		return arrays;
	}
	
	
	/**
	 * 获取性别
	 * */
	private Integer getSexType(String sex) {
		if(!StringUtils.isEmpty(sex))
		{
			if("未知".equals(sex))
			{
				return 0;
			}
			if("男".equals(sex))
			{
				return 1;
			}
			else if("女".equals(sex))
			{
				return 2;
			}
		}
		return 0;
	}
	
	public Map<String,Object> calPhysicalScore(PhysicalDto physical,Long orgId,Long gradeId, Byte gender, String achievement)
	{

		log.info(" matched(physical:" + physical.getId() + ", org:" + orgId + ")");

		Map<String,Object> map = new HashMap<>();
		double ach = 0;

		try{
			ach = SportsUtils.translate(physical.getUnit(), achievement);
		}catch(Throwable e) {
			log.error("calPhysicalScore",e);
		}
		List<PhysicalRuleDto> rules = physical.getRuleList();
		if(rules == null) {
			log.error("calPhysicalScore 没有规则");
		}

		for(PhysicalRuleDto rule : rules) {
			if(compareValue(rule.getGradeId(), gradeId) && (rule.getSex() == 0 || compareValue(rule.getSex(), gender))) {
				log.info(" matched(rule:" + rule.getId() + ", grade:" + rule.getGradeId() + ", sex:" + rule.getSex() + ", ruleType:" + rule.getRuleType() + ") weight:" + rule.getWeight());
				List<PhysicalRuleItemDto> items = rule.getItemDtoList();
				if(items == null) {
					continue;
				}
				getScoreMark(map, rule.getRuleType(), items, ach);
				List<PhysicalRulePlusesDto> pluses = rule.getPlusesList();
				if(pluses == null) {
					continue;
				}
				getPlusMark(map, rule.getRuleType(), pluses, ach);
			}
		}

		return map;
	}
	
	
	
	private void getPlusMark(Map<String,Object> map, int ruleType, List<PhysicalRulePlusesDto> items, double achievement) {
		double value;
		int result;
		if(ruleType == SportsRuleTypeEnum.DESC.getValue()) {
			value = 99999;
			for(PhysicalRulePlusesDto item : items) {
				if(item.getMax() == value) {
					value = item.getMin();
					map.put("plusesScore",String.valueOf((int)(item.getScore() + 100)));
					map.put("plusesMarksScore",String.valueOf((int)(item.getScore() + 100)));
					break;
				}
			}
			log.info(" desc plusMarks -> value:" + value + ", achievement:" + achievement);
			result = (int)( value > achievement ? value - achievement : 0);
		}else {
			value = 0;
			for(PhysicalRulePlusesDto item : items) {
				if(item.getMin() == value) {
					value = item.getMax();
					map.put("plusesScore",String.valueOf((int)(item.getScore() + 100)));
					map.put("plusesMarksScore",String.valueOf((int)(item.getScore() + 100)));
					break;
				}
			}
			log.info(" plusMarks -> value:" + value + ", achievement:" + achievement);
			result = (int)( achievement > value ? achievement - value : 0);
		}
		map.put("plusesValue",String.valueOf((int)value));
		map.put("plusesAchievement",String.valueOf(result));
		map.put("plusesMarksValue",String.valueOf((int)value));
	}
	
	
	private void getScoreMark(Map<String,Object> map, int ruleType, List<PhysicalRuleItemDto> items, double achievement) {

		double value;
		int result;
		if(ruleType == SportsRuleTypeEnum.DESC.getValue()) {
			value = 99999;
			for(PhysicalRuleItemDto item : items) {
				if(item.getMax() == value) {
					value = item.getMin();
					map.put("fullScore",item.getScore());
					map.put("fullMarksScore",item.getScore());
					break;
				}
			}
			log.info(" desc fullMarks -> value:" + value + ", achievement:" + achievement);
			result = (int)(value > achievement ? value - achievement : 0);
		}else {
			value = 0;
			for(PhysicalRuleItemDto item : items) {
				if(item.getMin() == value) {
					value = item.getMax();
					map.put("fullScore",item.getScore());
					map.put("fullMarksScore",item.getScore());
					break;
				}
			}
			log.info(" fullMarks -> value:" + value + ", achievement:" + achievement);
			result = (int)(value > achievement ? achievement - value : 0);
		}
		map.put("fullValue",String.valueOf((int)value));
		map.put("fullAchievement",String.valueOf((int)result));
		map.put("fullMarksValue",String.valueOf((int)value));
	}
}
